package org.jd.export.controller;

import lombok.RequiredArgsConstructor;
import org.jd.export.model.TableInfo;
import org.jd.export.service.SchemaService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class SchemaController {

    private final SchemaService schemaService;
    
    @Value("${spring.datasource.url}")
    private String jdbcUrl;

    /**
     * 从JDBC URL中提取数据库名称
     */
    public String extractDatabaseName() {
        String dbName = "";
        if (jdbcUrl.contains("jdbc:mysql://")) {
            String[] parts = jdbcUrl.split("/");
            if (parts.length > 3) {
                dbName = parts[3].split("\\?")[0];
            }
        }
        return dbName;
    }

    /**
     * 获取当前数据库中所有表的结构信息
     */
    @GetMapping("/api/tables")
    public List<TableInfo> getAllTables() {
        String databaseName = extractDatabaseName();
        return schemaService.getAllTablesInSchema(databaseName);
    }
}
